package com.jy.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jy.oss.service.OssService;
import com.jy.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author GrainProjectTeam
 * @create 2020 - 12 - 10  22:25
 * getInputStream: 获取文件上传的输入流
 * getOriginalFilename: 获取文件真实名称
 */
@Service
public class OssServiceImpl implements OssService {

    @Override // 上传头像 --> OSS
    public String uploadOssFileAvatar(MultipartFile file) {
        /**
         * Take Hangzhou as an example for Endpoint.
         * Please fill in other regions according to actual conditions.
         * Cloud account AccessKey has all API access permissions.
         * It is recommended to follow Alibaba Cloud security best practices and create
         * and use RAM sub-accounts for API access or daily operation and maintenance.
         * Please log in to https://ram.console.aliyun.com to create.
         */
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            // 创建OSS客户端实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            // 使用uuid添加随机唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            // 将文件按照层级日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSS客户端
            ossClient.shutdown();
            // https://edu4869.oss-cn-chengdu.aliyuncs.com/19151405.png
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
